<template>
  <div>
    <div class="logo"></div>
    <van-form>
      <van-cell-group inset>
        <van-field
          v-model="userinfo.account"
          label="用户名"
          placeholder="请输入手机号"
          :rules="usernameRules"
        >
        </van-field>
        <van-field
          v-model="userinfo.password"
          label="密码"
          type="password"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
    </van-form>
    <div class="logn_btn fts1 tc" @click="goLogin">登录</div>
    <p class="tc mt1 fts1">
      还没有账号?<span class="link_color" @click="goRegister">点击注册</span>
    </p>
  </div>
</template>

<script>
import {
  Form,
  Field,
  CellGroup,
  Toast,
  showToast,
  showLoadingToast,
} from 'vant'
import routerURL from '@/router/routerURL'
import api from '@/api/api.js'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export default {
  components: {
    [showToast.name]: showToast,
    [Toast.name]: Toast,
    [Form.name]: Form,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [showLoadingToast.name]: showLoadingToast,
  },
  setup() {
    const userinfo = ref({ account: '', password: '' })
    const router = useRouter()

    const usernameRules = [
      {
        pattern: /^1[3456789]\d{9}$/, // 手机号正则表达式
        message: '手机号格式错误', // 验证失败提示信息
      },
    ]

    const goLogin = () => {
      if (!userinfo.value.account || !userinfo.value.password) {
        showToast('请填写完整登录信息')
        return
      }
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 1000,
      })
      api.loginApi(userinfo.value).then((res) => {
        if (res.status === 200) {
          window.localStorage.setItem('token', res.token)
          window.localStorage.setItem('name', res.name)
          // 添加延时跳转
          setTimeout(() => {
            router.push({ path: routerURL.HOME })
          }, 1000)
        }
      })
    }

    const goRegister = () => {
      router.push({ path: routerURL.REGISTER })
    }

    return {
      userinfo,
      usernameRules,
      goLogin,
      goRegister,
    }
  },
}
</script>

<style scoped>
.logo {
  width: 11rem;
  height: 11rem;
  background: url('../assets/huanbei_logo.png') no-repeat;
  background-size: cover;
  margin: 4rem auto 2rem auto;
}
</style>
